package cn.zhaoyuening.algorithms.queue;

import java.util.LinkedList;
import java.util.Queue;

/**
 * Created by Buynow on 2017/8/6.
 */
public class PetQueue {
    private Queue<Pet> queue = new LinkedList<>();
    private int dogCounter = 0;
    private int catCounter = 0;

    public boolean isEmpty() {
        return queue.isEmpty();
    }

    public boolean isDogEmpty() {
        return dogCounter <= 0;
    }

    public boolean isCatEmpty() {
        return catCounter <= 0;
    }

    public Pet pollAll() {
        Pet p = queue.poll();
        if (p == null) {
            return p;
        }
        if (p instanceof Dog) {
            dogCounter--;
        }else if (p instanceof Cat){
            catCounter--;
        }
        return p;
    }

    public Dog pollDog() {
        if (dogCounter == 0) {
            return null;
        }
        return (Dog) getPetInQueue("dog");
    }

    public Cat pollCat() {
        if (catCounter == 0) {
            return null;
        }
        return (Cat) getPetInQueue("cat");
    }

    public void add(Pet pet) {
        if (pet instanceof Dog) {
            dogCounter++;
        } else if (pet instanceof Cat) {
            catCounter++;
        }

        queue.add(pet);
    }

    public Pet getPetInQueue(final String type) {
        if (queue.isEmpty()) {
            return null;
        }
        Pet p = queue.poll();
        Pet result = p;
        if (!result.getType().equals(type)) {
            queue.add(p);
            result = getPetInQueue(type);
        }
        if (result != null) {
            if (result instanceof Cat) {
                catCounter--;
            } else if (result instanceof Dog) {
                dogCounter--;
            }
        }
        return result;
    }

    public int getCatCounter() {
        return catCounter;
    }

    public int getDogCounter() {
        return dogCounter;
    }

    public static void main(String[] args) {
        PetQueue queue = new PetQueue();
        queue.add(new Dog());
        queue.add(new Dog());
        queue.add(new Cat());
        queue.add(new Dog());
        queue.add(new Cat());

        System.out.println(queue.getCatCounter());
        System.out.println(queue.getDogCounter());
        queue.pollCat();
        queue.pollDog();
        System.out.println(queue.getCatCounter());
        System.out.println(queue.getDogCounter());
    }
}



abstract class  Pet{
    private String type;

    public String getType() {
        return type;
    }

    public Pet(String type) {
        this.type = type;
    }
}

class Dog extends Pet{

    public Dog() {
        super("dog");
    }
}


class Cat extends Pet{

    public Cat() {
        super("cat");
    }
}

